<template>
  <!-- 回收管理 -->
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="csmType" style="width: 170px; margin-right: 2px;">
          <el-option label="单据号" value="billCode" />
          <el-option label="客户编号" value="csmCode" />
        </el-select>
        <el-input v-model.trim="csmText" placeholder="请输入" clearable />
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item" label="回收时间:">
        <el-date-picker
          v-model="date"
          type="daterange"
          unlink-panels
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        />
      </el-form-item>
      <el-form-item label="回收机构:" prop="orgSNNo">
        <el-tree-select
          v-model="query.orgSNNo"
          clearable
          class="tree-select"
          :popover-width="360"
          :select-params="{
            clearable: true,
            placeholder: '请选择',
            loading: $loadingPlugin.getTreeData,
          }"
          :tree-params="{
            'expand-on-click-node': false,
            'highlight-current': true,
            'filterable': true,
            props: {
              value: 'orgSNNo',
              label: 'orgName',
              disabled: 'disabled',
            },
            data: treeData,
          }"
        />
      </el-form-item>
      <el-form-item label="单据状态:" prop="billStatus">
        <el-select v-model="query.billStatus" clearable placeholder="请选择">
          <el-option
            v-for="item in orderStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="单据类型:" prop="billType">
        <el-select v-model="query.billType" clearable placeholder="请选择">
          <el-option
            v-for="item in billTypeMap"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button
          v-permission="1"
          type="primary"
          icon="el-icon-search"
          @click="search"
        >查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 20px;">
      <div>
        <el-button
          v-permission="2"
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="openRecallOrderAdd(1)"
        >回收</el-button>
        <el-button
          v-permission="3"
          type="primary"
          icon="el-icon-circle-plus-outline"
          @click="openRecallOrderAdd(2)"
        >退残</el-button>
        <el-button
          v-permission="9"
          type="primary"
          icon="el-icon-download"
          @click="exportFile"
        >导出</el-button>
        <!-- <el-button type="primary" icon="el-icon-printer" @click="print">打印</el-button> -->
      </div>
    </div>

    <!-- 表单 -->
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      class="table"
      border
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <csm-detail ref="csmDetail" :tree-data="treeData" :calc-type-list="calcTypeList" :paymen-fil-list="paymenFilList" />
    <recallOrderDetails ref="recallOrderDetails" />
    <retiringOrderDetail ref="retiringOrderDetail" />
    <recallOrder ref="recallOrder" :payment-method-map="paymenFilList" />
    <retiringOrder ref="retiringOrder" :payment-method-map="paymenFilList" />
  </div>
</template>

<script>
  import {
    queryExportRecycleList,
    queryRecycleOrderList,
    recycleOrderDelete,
    recycleOrderGetSessionID,
    queryRejectRecycleOrder,
    queryMap
  } from '@/api'
  import getTreeData from '@/utils/jsonTree'
  import { parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { mapGetters } from 'vuex'
  import RecallOrderDetails from './components/RecallOrderDetails'
  import RetiringOrderDetail from './components/RetiringOrderDetail'
  import RecallOrder from './components/RecallOrder'
  import RetiringOrder from './components/RetiringOrder'
  import CsmDetail from '../../components/CsmDetailModal/index.vue'
  import { formatColumnMap } from '@/utils'
  import moment from 'dayjs'
  import axios from 'axios'

  export default {
    name: 'recoveryManage',
    components: {
      RecallOrderDetails,
      RecallOrder,
      CsmDetail,
      RetiringOrder,
      RetiringOrderDetail
    },
    data() {
      return {
        actionColWidth: 80,
        treeData: [],
        paymenFilList: [],
        orderStatusMap: [
          {
            value: 1,
            desc: '待审核'
          },
          {
            value: 2,
            desc: '已审核'
          },
          {
            value: 3,
            desc: '已驳回'
          },
          {
            value: -1,
            desc: '作废'
          }
        ],
        date: [moment().startOf('day'), moment().endOf('day')],
        csmType: 'billCode',
        csmText: '',
        query: {
          orgSNNo: '',
          billStatus: '',
          billType: ''
        },
        roleTypeList: [],
        calcTypeList: [],
        billTypeMap: [
          {
            value: 1,
            label: '回收'
          },
          {
            value: 2,
            label: '退残'
          }
        ],
        searchParams: {},
        tableData: {
          total: 0,
          data: []
        },
        frameData: {}
      }
    },
    computed: {
      ...mapGetters(['orgList', 'corpSettingData', 'exportDomain']),
      column: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'billCode',
            label: '单据号',
            width: 180,
            render: (h, { row }) => (
            <el-link underline={false} onClick={() => this.openRecallOrderDetails(row)}>
              {row.billCode}
            </el-link>
          )
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            render: (h, { row }) => (
              <el-link underline={false} onClick={() => this.openCsmDetail(row)}>
                {row.csmCode}
              </el-link>
            )
          },
          {
            prop: 'csmName',
            label: '客户名称',
            width: 110
          },
          {
            prop: 'csmPhone',
            label: '联系方式',
            width: 110
          },
          {
            prop: 'csmAddress',
            label: '地址',
            width: 200
          },
          {
            prop: 'orgName',
            label: '回收机构',
            width: 150
          },
          {
            prop: 'targetUser',
            label: '回收人'
          },
          {
            prop: 'totalAmount',
            label: '费用金额',
            aligh: 'right',
            formatter: function(row) {
              if (!row.reclTotalAmount) {
                row.reclTotalAmount = 0
              }
              if (!row.substituteAmount) {
                row.substituteAmount = 0
              }
              return Number(row.substituteAmount - row.reclTotalAmount).toFixed(2)
            }
          },
          {
            prop: 'happendTime',
            label: '回收时间',
            width: 140,
            render: (h, { row }) => (
            <span>
              {row.happendTime && parseTime(row.happendTime, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          },
          {
            prop: 'paymentMethod',
            label: '支付方式',
            render: (h, { row }) => (
            <span>
              {row.paymentMethod &&
                formatColumnMap(
                  this.paymenFilList,
                  'value',
                  row.paymentMethod,
                  'desc'
                )}
            </span>
          )
          },
          {
            prop: 'remark',
            label: '备注',
            width: 110
          },
          {
            prop: 'billStatus',
            label: '单据状态',
            render: (h, { row }) => (
            <span>
              {formatColumnMap(this.orderStatusMap, 'value', row.billStatus, 'desc')}
            </span>
          )
          },
          {
            prop: 'billType',
            label: '单据类型',
            width: 110,
            render: (h, { row }) => (
            <span>
              {row.billType &&
                formatColumnMap(this.billTypeMap, 'value', row.billType, 'label')}
            </span>
            )
          },
          {
            prop: 'auditTime',
            label: '审核时间',
            width: 140,
            render: (h, { row }) => (
            <span>
              {row.auditTime && parseTime(row.auditTime, '{y}-{m}-{d} {h}:{i}')}
            </span>
          )
          },
          {
            prop: 'orderCode',
            label: '关联订单号',
            width: 110
          },
          {
            label: '操作',
            fixed: 'right',
            className: 'action-col',
            width: this.actionColWidth,
            render: (h, { row, $index }) => {
              return (
              <div>
                <el-dropdown>
                  <span class='el-dropdown-link'>
                    更多<i class='el-icon-arrow-down el-icon--right'></i>
                  </span>
                  <el-dropdown-menu slot='dropdown'>
                    <el-dropdown-item>
                      {(row.billStatus === 1 || row.billStatus === 3) && (
                        <el-link
                          v-permission='4'
                          underline={false}
                          size='mini'
                          onClick={() => this.update(row, $index)}
                        >
                          编辑
                        </el-link>
                      )}
                    </el-dropdown-item>
                    <el-dropdown-item>
                      {((this.corpSettingData.sp5 >> 6) & 0x01) === 0 && row.billStatus === 1 && (
                        <el-link
                          v-permission='5'
                          underline={false}
                          size='mini'
                          onClick={() => this.audit(row, $index)}
                        >
                          审核
                        </el-link>
                      )}
                    </el-dropdown-item>
                    <el-dropdown-item>
                      {((this.corpSettingData.sp5 >> 6) & 0x01) === 0 && row.billStatus === 1 && (
                        <el-link
                          v-permission='6'
                          underline={false}
                          size='mini'
                          onClick={() => this.del(row, $index)}
                        >
                          作废
                        </el-link>
                      )}
                    </el-dropdown-item>
                    <el-dropdown-item>
                      {((this.corpSettingData.sp5 >> 6) & 0x01) === 0 && row.billStatus === 2 && (
                        <el-link
                          v-permission='7'
                          underline={false}
                          size='mini'
                          onClick={() => this.cancelAudit(row, $index)}
                        >
                          反审核
                        </el-link>
                      )}
                    </el-dropdown-item>
                    <el-dropdown-item>
                      { row.billStatus !== -1 && (
                        <el-link
                          v-permission='8'
                          underline={false}
                          size='mini'
                          onClick={() => this.print(row, $index)}
                        >
                          打印
                        </el-link>
                      )}
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown>
              </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.getTreeData(), this.getRecycleOrderFrameData(), this.queryData()])
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage, pageSize }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        if (this.date && this.date.length === 2) {
          query.createTime = this.date[0]
          query.createTimeEnd = this.date[1]
          const diff = moment(this.date[1]).diff(moment(this.date[0]), 'days')
          if (diff > 366) {
            this.$message.error('回收时间最大支持查询1年')
            return
          }
        }
        query[this.csmType] = this.csmText
        const res = await queryRecycleOrderList(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 获取枚举
      async queryData() {
        const [res1, res2] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'PaymentMethod' }),
          mergeAsyncFunc(queryMap, { enumName: 'CalcType' })
        ])
        this.paymenFilList = res1.data.filter(item => item.value === 1 || item.value === 2 || item.value === 16 || item.value === 128 || item.value === 256 || item.value === 2048) // 支付方式
        this.calcTypeList = res2.data // 收款方式
      },
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.map((item) => ({
          label: item.name,
          ...item
        }))
        this.treeData = getTreeData(data)
      },
      async getRecycleOrderFrameData() {
        axios.post(process.env.VUE_APP_BASE_API + '/proxy/inven/recycle/frame').then(res => {
          console.log(res)
          if (res.status === 200) {
            this.frameData = res.data
            // this.orderStatusMap = JSON.parse(res.data.billStatusMap) // 单据状态
            // this.paymenFilList = JSON.parse(res.data.paymenFilList) // 支付方式
          }
        })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 点击客户编码
      async openCsmDetail(row) {
        await this.$refs.csmDetail.open(row)
      },
      // 新增
      async openRecallOrderAdd(type) {
        if (type === 1) {
          await this.$refs.recallOrder.open('', 'add')
          this.$refs.lbTable.fetch({ currentPage: 1 })
        } else {
          await this.$refs.retiringOrder.open('', 'add')
          this.$refs.lbTable.fetch({ currentPage: 1 })
        }
      },
      // 编辑
      async update(row) {
        console.log(row)
        if (row.billType === 1) {
          await this.$refs.recallOrder.open(row, 'edit')
          this.$refs.lbTable.fetch({ currentPage: 1 })
        } else {
          await this.$refs.retiringOrder.open(row, 'edit')
          this.$refs.lbTable.fetch({ currentPage: 1 })
        }
      },
      // 审核
      async audit(row) {
        if (row.billType === 1) {
          await this.$refs.recallOrder.open(row, 'audit')
          this.$refs.lbTable.fetch()
        } else {
          await this.$refs.retiringOrder.open(row, 'audit')
          this.$refs.lbTable.fetch()
        }
      },
      // 回收单详情
      async openRecallOrderDetails(row) {
        if (row.billType === 1) {
          await this.$refs.recallOrderDetails.open(row)
        } else {
          await this.$refs.retiringOrderDetail.open(row)
        }
      },
      // 反审核
      cancelAudit(row, index) {
        this.$confirm('确是否确定执行反审核操作？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在操作',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          queryRejectRecycleOrder({ billCode: row.billCode })
            .then(() => {
              this.$notify({
                title: '提示',
                message: '操作成功',
                type: 'success',
                duration: 2000
              })
              this.search()
            })
            .finally(() => {
              loading.close()
            })
        })
      },
      del(row, index) {
        this.$confirm('确认要作废该回收单吗？', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$message({
            message: '正在作废',
            duration: 0,
            iconClass: 'el-icon-loading'
          })
          recycleOrderDelete({ billCode: row.billCode })
            .then(() => {
              this.$refs.lbTable.fetch({ currentPage: 1 })
              this.$notify({
                title: '提示',
                message: '作废成功',
                type: 'success',
                duration: 2000
              })
            })
            .finally(() => {
              loading.close()
            })
        })
      },
      // 导出
      exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.column))
          copyColumn.pop()
          const str = {}
          copyColumn.forEach((item) => {
            str[item.prop] = item.label
          })
          const query = {
            paramInfo: _this._getQuery(_this.searchParams),
            kv: str // 表格列
          }
          query.paramInfo.billStatus = _this.query.billStatus ? _this.query.billStatus : '0'
          query.paramInfo.billType = _this.query.billType ? _this.query.billType : '0'
          queryExportRecycleList(query).then((res) => {
            window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      // 打印
      async print(row) {
        const obj = {
          reportlet: '52013/回收单.cpt',
          billCode: row.billCode,
          corpSN: row.corpSN,
          database: this.frameData.database
        }
        const params = {
          json: JSON.stringify(obj)
        }
        const { status, data } = await recycleOrderGetSessionID(params)
        if (status === 200) {
          if (!data) {
            this.$message.error('打印失败,请重试')
            return
          }
          const tempWin = window.open()
          tempWin.location =
            this.frameData.reportUrl + '?op=fr_pdfprint&cmd=native&sessionID=' + data
        }
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach((it) => {
                width += it.offsetWidth + 10
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
  .merge-item {
    /deep/ .el-form-item__content {
      display: flex;
    }
  }
</style>
